<template>
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="allCheck"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- These are here just to show the structure of the list items -->
      <!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
      <li
        :class="{ completed: item.isDone, editing: currentId === item.id }"
        v-for="item in showList"
        :key="item.id"
      >
        <div class="view">
          <input
            class="toggle"
            type="checkbox"
            :checked="item.isDone"
            @change="change(item.id)"
          />
          <label @dblclick="dblclick(item)">{{ item.name }}</label>
          <button class="destroy" @click="del(item.id)"></button>
        </div>
        <input
          class="edit"
          v-model="currentName"
          @keyup.esc="cancel"
          @keyup.enter="edit"
          v-focus
        />
      </li>
    </ul>
  </section>
</template>

<script>
export default {
  directives: {
    focus: {
      // 指令的定义
      update: function (el) {
        el.focus();
      },
    },
  },
  props: {
    list: {
      type: Array,
      required: true,
    },
    type: {
      type: String,
      default: "all",
    },
  },
  data() {
    return {
      currentId: "",
      currentName: "",
    };
  },
  methods: {
    del(id) {
      this.$emit("del", id);
    },
    change(id) {
      this.$emit("change", id);
    },
    dblclick(item) {
      this.currentId = item.id;
      this.currentName = item.name;
    },
    cancel() {
      this.currentId = "";
    },
    edit() {
      this.$emit("edit", this.currentId, this.currentName);
      this.currentId = "";
    },
  },
  computed: {
    showList() {
      if (this.type === "active") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === "completed") {
        return this.list.filter((item) => item.isDone);
      } else {
        return this.list;
      }
    },
    allCheck: {
      get() {
        return this.list.every((item) => item.isDone);
      },
      set(value) {
        this.$emit("set", value);
      },
    },
  },
};
</script>

<style>
</style>